<script lang="ts" setup>
import { get, post, Message, loadFile, message } from '@/utils'
import isEmpty from 'lodash/isEmpty'
const props = defineProps<{ info: Product }>()

/**是否是单规格商品 0否1是 */
const _isSingular = ref(1)
const alert = reactive({
  show: false,
  value: '规格数据有变动，请重新点击上方 [刷新规格项目表] 按钮！',
})
const formData = reactive({
  goodsSkuList: [] as any[],
  singularGoodsSkuList: [] as any, //单规格类型的
  goodsSpecKeyList: [
    {
      specKey: '默认',
      goodsSpecList: [{ specKey: '默认', specValue: '默认' }],
    },
  ],
  keys: [''],
})
watch(
  () => _isSingular.value,
  n => {
    if (n == 1) {
      console.log('watch')

      formData.singularGoodsSkuList = [spaceItemDefault()]
    }
  }
)
//设置默认规格
const skuListItemDefault = () => ({
  specKey: '',
  goodsSpecList: [skuSpecItemDefault()],
})
//默认规格项
const skuSpecItemDefault = (key = '') => ({ specKey: key, specValue: '' })
//默认价格相关
const spaceItemDefault = (name = '{默认:默认}') => {
  return {
    spec: name,
    marketPrice: 0,
    goodsPrice: 0,
    volume: 0,
    weight: 0,
    stock: 0,
    costPrice: 0,
    img: '',
  }
}
//快捷设置规格相关价格
const defaultVals = reactive({
  marketPrice: 0,
  goodsPrice: 0,
  volume: 0,
  weight: 0,
  stock: 0,
  costPrice: 0,
})

const initSpec = () => {
  if (!isEmpty(props.info)) {
    const { goodsSkuList } = props.info
    /**区分单/多规格处理 */
    _isSingular.value = !props.info.goodsSpecKeyList.length ? 1 : 0
    console.log('🚀 ~ file: ProductSpec.vue:64 ~ initSpec ~ _isSingular:', _isSingular)
    if (!props.info.goodsSpecKeyList.length) {
      console.log('单规格')
      goodsSkuList.map(v => {
        const obj = v.spec ? JSON.parse(v.spec) : {}
        const values = Object.values(obj)
        v.spec = values.join('+')
      })
      console.log('🚀 ~ file: ProductSpec.vue:71 ~ goodsSkuList.map ~ goodsSkuList:', goodsSkuList)
      formData.singularGoodsSkuList = [goodsSkuList[0]]
    } else {
      console.log('多规格')
      formData.goodsSpecKeyList = props.info.goodsSpecKeyList
      goodsSkuList.map((v: any) => {
        v.specName = v.spec
        const obj = v.spec ? JSON.parse(v.spec) : {}
        const values = Object.values(obj)
        v.spec = values.join('+')
      })
      ganerateSpecList()
      formData.goodsSkuList = goodsSkuList
      console.log(formData)
    }
  }
}
watch(
  () => props.info,
  () => initSpec()
)

/**
 *
 * @param key
 */
const setDefaultVal = key => {
  console.log('🚀 ~ setDefaultVal ~ key:', key)
  formData.goodsSkuList.forEach(item => {
    item[key] = defaultVals[key]
  })
  console.log('🚀 ~ setDefaultVal ~ formData:', formData)
}

/**监听规格变化提示 */
watch(
  () => formData.goodsSpecKeyList,
  () => (alert.show = true),
  { deep: true }
)
/**递归合并数组 */
function generateCombinations(specs) {
  let result: any[] = []

  // 递归函数用于组合规格
  function combine(combination = {}, index = 0) {
    // 如果当前索引超过了规格数组的长度，说明已经组合完成
    if (index === specs.length) {
      result.push({
        specName: JSON.stringify(combination),
        spec: Object.values(combination).join('+'),
      })
      return
    }
    // 获取当前规格下的所有可能值
    const currentSpec = specs[index]
    const specKey = currentSpec.specKey
    // 遍历当前规格的所有值，并递归调用combine函数
    currentSpec.goodsSpecList.forEach(specValueObj => {
      const specValue = specValueObj.specValue
      const newCombination = { ...combination, [specKey]: specValue }
      combine(newCombination, index + 1)
    })
  }

  // 开始递归
  combine()

  return result
}
/**生成全部规格列表 */
const ganerateSpecList = () => {
  const keys: string[] = []
  formData.goodsSpecKeyList.map((sku, index) => {
    keys.push(sku.specKey)
    sku.goodsSpecList.map(item => {
      item.specKey = sku.specKey
    })
  })
  const result: any[] = []
  const res = generateCombinations(formData.goodsSpecKeyList)
  res.map(v => {
    result.push({
      ...spaceItemDefault(v.spec),
      specName: v.specName,
    })
  })
  formData.goodsSkuList = result
  formData.keys = keys

  nextTick(() => {
    alert.show = false
  })
}
/**删除商品规格 */
const removeSpecItem = (index, index2) => {
  console.log(formData.goodsSpecKeyList[index].goodsSpecList)
  const len = formData.goodsSpecKeyList[index].goodsSpecList.length
  if (index2 == 0 && len == 1) {
    message({
      type: 'error',
      content: '必须保留一项规格',
    })
  } else formData.goodsSpecKeyList[index].goodsSpecList.splice(index2, 1)
}
onMounted(() => {
  if (isEmpty(props.info)) {
    ganerateSpecList()
    formData.singularGoodsSkuList = [spaceItemDefault()]
  }
})
defineExpose({
  data: formData,
  alert: alert.show,
  isSingular: () => _isSingular.value == 1,
})
</script>
<template>
  <main>
    <a-form :model="{}" :label-col-props="{ span: 3 }" :wrapper-col-props="{ span: 21 }" style="width: 100%">
      <a-form-item label="规格类型">
        <a-radio-group
          v-model="_isSingular"
          :options="[
            { label: '单规格', value: 1 },
            { label: '多规格', value: 0 },
          ]"
        ></a-radio-group>
      </a-form-item>
      <template v-if="_isSingular == 0">
        <a-form-item>
          <div class="btn-box flex">
            <a-button type="primary" style="margin-right: 10px" @click="formData.goodsSpecKeyList.push(skuListItemDefault())">
              <template #icon>
                <icon-plus />
              </template>
              添加规格</a-button
            >
            <a-button type="primary" @click="ganerateSpecList">
              <template #icon>
                <icon-refresh />
              </template>
              刷新价格表</a-button
            >
          </div>
        </a-form-item>
        <a-form-item label="商品规格" v-for="(item, index) in formData.goodsSpecKeyList">
          <div style="flex: 1">
            <a-input v-model="item.specKey" placeholder="请输入规格标题：（比如：颜色、尺寸）">
              <template #append>
                <div class="flex btn-box">
                  <a-button type="primary" @click="item.goodsSpecList.push(skuSpecItemDefault(item.specKey))">
                    <template #icon>
                      <icon-plus />
                    </template>
                    添加规格项</a-button
                  >
                  <a-button type="primary" status="danger" @click="formData.goodsSpecKeyList.splice(index, 1)">
                    <template #icon>
                      <icon-delete />
                    </template>
                  </a-button>
                </div>
              </template>
            </a-input>
            <div class="item-list grid-5">
              <div class="item" v-for="(item2, index2) in item.goodsSpecList">
                <a-input v-model="item2.specValue" placeholder="请输入规格名称">
                  <template #append>
                    <a-button type="primary" status="danger" @click="removeSpecItem(index, index2)">
                      <template #icon>
                        <icon-delete />
                      </template>
                    </a-button>
                  </template>
                </a-input>
              </div>
            </div>
          </div>
        </a-form-item>
        <a-form-item>
          <a-alert type="warning" v-if="alert.show">警告：{{ alert.value }}</a-alert>
        </a-form-item>
        <div class="spec-list">
          <a-form-item label="规格">
            <div class="spec-title grid-5">
              <div class="item flex-center input-box">
                <span style="margin: auto"> 规格图片</span>
              </div>
              <div class="item flex-center input-box">
                <span> 展示价格</span>
                <a-input-number :min="0" hide-button v-model="defaultVals.goodsPrice">
                  <template #append>
                    <a-button type="primary" @click="setDefaultVal('goodsPrice')">
                      <template #icon>
                        <icon-arrow-down />
                      </template>
                    </a-button>
                  </template>
                </a-input-number>
              </div>
              <div class="item input-box flex-center input-box">
                <span>划线价格</span>
                <a-input-number :min="0" hide-button v-model="defaultVals.marketPrice">
                  <template #append>
                    <a-button type="primary" @click="setDefaultVal('marketPrice')">
                      <template #icon>
                        <icon-arrow-down />
                      </template>
                    </a-button>
                  </template>
                </a-input-number>
              </div>
              <div class="item input-box flex-center input-box">
                <span>成本价格</span>
                <a-input-number :min="0" hide-button v-model="defaultVals.costPrice">
                  <template #append>
                    <a-button type="primary" @click="setDefaultVal('costPrice')">
                      <template #icon>
                        <icon-arrow-down />
                      </template>
                    </a-button>
                  </template>
                </a-input-number>
              </div>
              <div class="item input-box flex-center input-box">
                <span>体积</span>
                <a-input-number :min="0" hide-button v-model="defaultVals.volume">
                  <template #append>
                    <a-button type="primary" @click="setDefaultVal('volume')">
                      <template #icon>
                        <icon-arrow-down />
                      </template>
                    </a-button>
                  </template>
                </a-input-number>
              </div>
              <div class="item input-box flex-center input-box">
                <span>重量</span>
                <a-input-number :min="0" hide-button v-model="defaultVals.weight">
                  <template #append>
                    <a-button type="primary" @click="setDefaultVal('weight')">
                      <template #icon>
                        <icon-arrow-down />
                      </template>
                    </a-button>
                  </template>
                </a-input-number>
              </div>
              <div class="item input-box flex-center input-box">
                <span>库存</span>
                <a-input-number :min="0" hide-button v-model="defaultVals.stock">
                  <template #append>
                    <a-button type="primary" @click="setDefaultVal('stock')">
                      <template #icon>
                        <icon-arrow-down />
                      </template>
                    </a-button>
                  </template>
                </a-input-number>
              </div>
            </div>
          </a-form-item>

          <a-form-item :label="item.spec" v-for="item in formData.goodsSkuList" :rules="[{ required: true }]">
            <div class="spec grid-5">
              <Upload :limit="1" :list="item.img" v-model:value="item.img" style="margin: auto" />
              <a-input-number :min="0" v-model="item.goodsPrice" />
              <a-input-number :min="0" v-model="item.marketPrice" />
              <a-input-number :min="0" v-model="item.costPrice" />
              <a-input-number :min="0" v-model="item.volume" />
              <a-input-number :min="0" v-model="item.weight" />
              <a-input-number :min="0" v-model="item.stock" />
            </div>
          </a-form-item>
        </div>
      </template>
      <template v-else>
        <div class="spec-list">
          <a-form-item label="规格">
            <div class="spec-title grid-5">
              <div class="item input-box">规格图片</div>
              <div class="item input-box">展示价格</div>
              <div class="item input-box">划线展示价格</div>
              <div class="item input-box">成本价格</div>
              <div class="item input-box">体积</div>
              <div class="item input-box">重量</div>
              <div class="item input-box">库存</div>
            </div>
          </a-form-item>

          <a-form-item label="默认" v-for="item in formData.singularGoodsSkuList" :rules="[{ required: true }]">
            <div class="spec grid-5">
              <Upload :limit="1" :list="item.img" v-model:value="item.img" style="margin: auto" />
              <a-input-number :min="0" v-model="item.goodsPrice" />
              <a-input-number :min="0" v-model="item.marketPrice" />
              <a-input-number :min="0" v-model="item.costPrice" />
              <a-input-number :min="0" v-model="item.volume" />
              <a-input-number :min="0" v-model="item.weight" />
              <a-input-number :min="0" v-model="item.stock" />
            </div>
          </a-form-item>
        </div>
      </template>
    </a-form>
  </main>
</template>
<style lang="less" scoped>
main {
  width: 90%;
  padding-top: 10px;
  margin: auto;
  color: rgb(144, 147, 153);
  // max-height: 60vh;
  // overflow-y: scroll;

  .grid-5 {
    padding-top: 10px;
    display: grid;
    // margin-bottom: 20px;
    grid-template-columns: repeat(5, 1fr);
    grid-column-gap: 10px;
    grid-row-gap: 10px;
  }

  .spec-list {
    .grid-5 {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      grid-row-gap: 10px;
      grid-column-gap: 10px;
      flex: 2;
      &.spec-title {
        :deep(.arco-input-number) {
          margin-left: 10px;
          flex: 1;
          margin-right: 10px;
        }
        .item {
          text-align: center;
        }
      }
      :deep(.arco-input-number) {
        margin: auto;
      }
    }
  }

  :deep(.arco-input-append) {
    padding-right: 0;
    padding-left: 0;
  }
  .btn-box {
    justify-content: flex-end;
  }
}
</style>
